#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <string.h>
#include <time.h>

#define SHM_KEY 0x1234
#define SHM_SIZE 4096
#define SEND_INTERVAL 5  // 发送间隔（秒）
#define MAX_SEND_COUNT 100  // 最大发送次数

// JSON模板字符串（使用三引号表示多行字符串）
const char* json_template = 
"{\n"
"    \"type\": 1,\n"
"    \"timestamp\": %ld,\n"
"    \"data\": [\n"
"        {\n"
"            \"sensor\": \"temperature\",\n"
"            \"val\": \"22.5\"\n"
"        },\n"
"        {\n"
"            \"sensor\": \"humidity\",\n"
"            \"val\": \"52.5\"\n"
"        },\n"
"        {\n"
"            \"sensor\": \"illuminance\",\n"
"            \"val\": \"2\"\n"
"        }\n"
"    ]\n"
"}";

int main() {
    // 创建共享内存
    int shm_id = shmget(SHM_KEY, SHM_SIZE, IPC_CREAT | 0666);
    if (shm_id == -1) {
        perror("shmget failed");
        exit(EXIT_FAILURE);
    }

    // 附加共享内存
    char* shm_ptr = shmat(shm_id, NULL, 0);
    if (shm_ptr == (char*)-1) {
        perror("shmat failed");
        exit(EXIT_FAILURE);
    }

    printf("Write端已启动，开始循环发送JSON数据...\n");
    
    for (int i = 0; i < MAX_SEND_COUNT; i++) {
        // 获取当前时间戳
        time_t timestamp = time(NULL);
        
        // 格式化JSON字符串（包含当前时间戳）
        snprintf(shm_ptr, SHM_SIZE, json_template, (long)timestamp);
        
        printf("[已发送 %d/%d]\n%s\n\n", i + 1, MAX_SEND_COUNT, shm_ptr);
        
        // 等待指定间隔
        sleep(SEND_INTERVAL);
    }

    printf("达到最大发送次数，退出中...\n");

    // 解除共享内存附加
    if (shmdt(shm_ptr) == -1) {
        perror("shmdt failed");
        exit(EXIT_FAILURE);
    }

    // 延迟确保读端完成操作
    sleep(1);
    
    // 删除共享内存
    if (shmctl(shm_id, IPC_RMID, NULL) == -1) {
        perror("shmctl failed");
        exit(EXIT_FAILURE);
    }
    printf("共享内存已释放\n");
    
    return EXIT_SUCCESS;
}